package com.example.ai.hmlmcp.tool;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.micrometer.common.util.StringUtils;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ImageSearchTool {
//    @Value(("${pexels.api.key}"))
//    private String API_KEY ;
    private  static  final String API_KEY = "oEMNJN1meC7DZxahhNnvQMJLIHhq6kex33i3RpJ3xBY5IXWIu3ai6iaJ";
    private  static  final String API_URL = "https://api.pexels.com/v1/search";

    @Tool(description = "Search image from web")
    public String searchImage(@ToolParam(description = "search query keyword") String query) {
        try {
            return String.join(",",searchMediumImage(query));
        }catch (Exception e){
           return"error seach image" + e.getMessage();
        }

    }

    public List<String> searchMediumImage(String query) {

            Map<String,String> headers = new HashMap<>();
            headers.put("Authorization", API_KEY);

            Map<String, Object> params = new HashMap<>();
            params.put("query", query);

            String response = HttpUtil.createGet(API_URL).addHeaders(headers).form(params).execute().body();

        return JSONUtil.parseObj(response)
                .getJSONArray("photos")
                .stream()
                .map(photoObj -> (JSONObject)photoObj)
                .map(photoObj -> photoObj.getJSONObject("src"))
                .map(photo -> photo.getStr("medium"))
                .filter(StringUtils::isNotEmpty)
                .collect(Collectors.toList());
    }

}
